/*
	Copyright (c) 2008, studiomagnolia.com - Cesare Rocchi
	All rights reserved.

	Redistribution and use in source and binary forms, with or without modification, 
	are permitted provided that the following conditions are met:

	- Redistributions of source code must retain the above copyright notice, this list 
		of conditions and the following disclaimer.
	- Redistributions in binary form must reproduce the above copyright notice, this list 
		of conditions and the following disclaimer in the documentation and/or other 
		materials provided with the distribution.
	- Neither the name of studiomagnolia.com nor the names of its contributors may 
		be used to endorse or promote products derived from this software without specific 
		prior written permission.

	THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
	AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
	IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
	ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 
	LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 
	DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 
	SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 
	CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 
	OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 
	OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

package com.studiomagnolia.focused.model {
	
	import flash.data.SQLConnection;
	import flash.data.SQLResult;
	import flash.data.SQLStatement;
	import flash.events.EventDispatcher;
	import flash.filesystem.File;
	import flash.net.FileFilter;
	
	public class Model extends EventDispatcher {
		
		private static var __instance:Model = new Model();
		public const textFilter:FileFilter = new FileFilter("Text Files (txt)","*.txt;");
		public const updaterUrl:String = "http://spreadingfunkyness.com/focused-download/update.xml";
		public var fileFullPath:String;
		public var closing:Boolean = false;
		private var _connection:SQLConnection;
		
		[Bindable (event="preferredFontSizeChanged")]
		private var _preferredFontSize:Number = 12;
		
		[Bindable (event="preferredFontFamilyChanged")]
		private var _preferredFontFamily:String = "Default";
		
		[Bindable (event="preferredFontColorChanged")]
		private var _preferredFontColor:String = "0xffffff";
		
		[Bindable (event="preferredAreaWidthChanged")]
		private var _preferredAreaWidth:Number = 100;
		
		[Bindable (event="preferredAreaHeightChanged")]
		private var _preferredAreaHeight:Number = 100;
		
		[Bindable] public var fileName:String = "Untitled";
		[Bindable] public var currentText:String = "";
		[Bindable] public var toBeSaved:Boolean = false;
		[Bindable] public var checkForUpdatesAtStartup:Boolean = true;
		[Bindable] public var playTypingSound:Boolean = false;
		[Bindable] public var showCharactersCount:Boolean = false;
		[Bindable] public var showWordsCount:Boolean = false;
		
		public function Model() {
			super();
			initDB();
		}
		
		public static function get instance():Model {
			return __instance;
		}
		
		[Bindable]
		public function set preferredFontColor(value:String):void {
			_preferredFontColor = value;
			dispatchEvent(new Event("preferredFontColorChanged"));
		}
		
		public function get preferredFontColor():String {
			return _preferredFontColor;
		}
		
		[Bindable]
		public function set preferredFontSize(value:Number):void {
			_preferredFontSize = value;
			dispatchEvent(new Event("preferredFontSizeChanged"));
		}
		
		public function get preferredFontSize():Number {
			return _preferredFontSize;
		}
		
		public function set preferredFontFamily(value:String):void {
			_preferredFontFamily = value;
			dispatchEvent(new Event("preferredFontFamilyChanged"));
		}
		
		public function get preferredFontFamily():String {
			return _preferredFontFamily;
		}
		
		[Bindable]
		public function set preferredAreaHeight(value:Number):void {
			_preferredAreaHeight = value;
			dispatchEvent(new Event("preferredAreaHeightChanged"));
		}
		
		public function get preferredAreaHeight():Number {
			return _preferredAreaHeight;
		}
		
		[Bindable]
		public function set preferredAreaWidth(value:Number):void {
			_preferredAreaWidth = value;
			dispatchEvent(new Event("preferredAreaWidthChanged"));
		}
		
		public function get preferredAreaWidth():Number {
			return _preferredAreaWidth;
		}
		
		
		private function initDB():void {
			var fileDB:File = File.applicationStorageDirectory.resolvePath("focusedSettings.db");
			_connection = new SQLConnection();
			_connection.open(fileDB);
			
			// create table
			var createSettingsTable:SQLStatement = new SQLStatement();
			createSettingsTable.sqlConnection = _connection;
			createSettingsTable.text = "CREATE TABLE IF NOT EXISTS SETTINGS" + 
					"(name TEXT PRIMARY KEY," + 
					"value TEXT" + 
					")";
			createSettingsTable.execute();
		}
		
		public function saveSettings():void {
			save("preferredFontColor", preferredFontColor);
			save("preferredFontSize", preferredFontSize.toString());
			save("preferredFontFamily", preferredFontFamily);
			save("preferredAreaHeight", preferredAreaHeight.toString());
			save("preferredAreaWidth", preferredAreaWidth.toString());
			
			if (checkForUpdatesAtStartup) {
				save("checkForUpdatesAtStartup", "1");
			} else {
				save("checkForUpdatesAtStartup", "0");
			}
			
			
			// save play typing sound settings
			if (playTypingSound) {
				save("playTypingSound", "1");
			} else {
				save("playTypingSound", "0");
			}
			
			// save characters count settings
			if (showCharactersCount) {
				save("showCharactersCount", "1");
			} else {
				save("showCharactersCount", "0");
			}
			
			// save characters count settings
			if (showWordsCount) {
				save("showWordsCount", "1");
			} else {
				save("showWordsCount", "0");
			}
		}
		
		public function loadSettings():void {
			if (read("preferredFontColor") != null) {
				preferredFontColor = read("preferredFontColor");
			}
			if (read("preferredFontSize") != null) {
				preferredFontSize = Number(read("preferredFontSize"));
			}
			if (read("preferredFontFamily") != null) {
				preferredFontFamily = read("preferredFontFamily");
			}
			if (read("checkForUpdatesAtStartup") != null) {
				if (read("checkForUpdatesAtStartup") == "0") {
					checkForUpdatesAtStartup = false;
				}
			}
			
			if (read("preferredAreaHeight") != null) {
				preferredAreaHeight = Number(read("preferredAreaHeight"));
			}
			if (read("preferredAreaWidth") != null) {
				preferredAreaWidth = Number(read("preferredAreaWidth"));
			}
			
			// load play typing sound settings
			if (read("playTypingSound") != null) {
				if (read("playTypingSound") == "1") {
					playTypingSound = true;
				}
			}
			
			// load show characters count settings
			if (read("showCharactersCount") != null) {
				if (read("showCharactersCount") == "1") {
					showCharactersCount = true;
				}
			}
			
			if (read("showWordsCount") != null) {
				if (read("showWordsCount") == "1") {
					showWordsCount = true;
				}
			}
		}
		
		private function save(optionName:String, optionValue:String):void {
			
			var setStatement:SQLStatement = new SQLStatement();
			setStatement.sqlConnection = _connection;
			setStatement.text = "REPLACE INTO SETTINGS (name, value) VALUES (:name, :value)";
			setStatement.parameters[":name"] = optionName;
			setStatement.parameters[":value"] = optionValue;
			setStatement.execute();
			
		}
		
		private function read(optionName:String):String {
			
			var readStatement:SQLStatement = new SQLStatement();
			readStatement.sqlConnection = _connection;
			readStatement.text = "SELECT * FROM SETTINGS WHERE name = :name";
			readStatement.parameters[":name"] = optionName;
			readStatement.execute();
			
			var res:SQLResult = readStatement.getResult();
			
			if (res.data != null && res.data.length > 0) {
				return res.data[0].value;
			}
			
			return null;
		}
	}
}